package com.hopu.erp.service.impl;

import com.hopu.erp.entity.Functions;
import com.hopu.erp.entity.Role;
import com.hopu.erp.entity.User;
import com.hopu.erp.service.FunctionsService;
import com.hopu.erp.service.RoleService;
import com.hopu.erp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Security自定义登录逻辑的实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private FunctionsService functionsService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUsername(username);
        if(user == null){
            throw new UsernameNotFoundException("用户名无效");
        }
        //查询角色
        List<Role> roles = roleService.findRolesByUsername(username);
        //查询权限
        List<Functions> functionsList = functionsService.findFunctionsByUsername(username);
        //将角色名和权限名拼接成字符串 xx,xxx,xxx,xxx,ROLE_
        StringBuilder strb = new StringBuilder();
        roles.forEach(role -> strb.append("ROLE_" + role.getName()+","));
        functionsList.forEach(functions -> strb.append(functions.getName()+","));
        strb.deleteCharAt(strb.length() - 1);
        //返回用户信息和授权列表
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(strb.toString()));
    }
}
